package com.xhtt.modules.app.controller.cfg;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.utils.Constant;
import com.xhtt.common.utils.ExportExcel;
import com.xhtt.common.utils.PageUtils;
import com.xhtt.common.utils.R;
import com.xhtt.modules.app.annotation.Login;
import com.xhtt.modules.app.annotation.LoginUser;
import com.xhtt.modules.cfg.entity.CfgPotInfo;
import com.xhtt.modules.cfg.entity.CfgPumpInfo;
import com.xhtt.modules.cfg.entity.CfgPumpProduct;
import com.xhtt.modules.cfg.entity.CfgPumpRelate;
import com.xhtt.modules.cfg.model.ValidPumpParam;
import com.xhtt.modules.cfg.service.CfgPumpInfoService;
import com.xhtt.modules.cfg.service.CfgPumpProductService;
import com.xhtt.modules.cfg.service.CfgPumpRelateService;
import com.xhtt.modules.sys.controller.AbstractController;
import com.xhtt.modules.sys.entity.SysUserEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 泵库 前端控制器
 * </p>
 *
 * @author feipc
 * @since 2019-02-20
 */
@Api(tags = "任务平台-基础数据维护-泵库列表", value = "任务平台-基础数据维护-泵库列表")
@RestController
@RequestMapping("app/sys/cfg/pump")
public class CfgPumpInfoController extends AbstractController {

    @Autowired
    private CfgPumpInfoService cfgPumpInfoService;
    @Autowired
    private CfgPumpProductService cfgPumpProductService;
    @Autowired
    private CfgPumpRelateService pumpRelateService;

    /**
     * 获取泵库列表
     */
    @GetMapping(value = "/list")
    @ApiOperation("获取泵库列表(web/app)")
    @Login
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgPumpInfoService.queryPage(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 新增泵库
     */
    @PostMapping(value = "/add")
    @ApiOperation("新增泵库(web)")
    @Login
    public R add(@RequestBody CfgPumpInfo cfgPumpInfo) {
        cfgPumpInfoService.addPump(cfgPumpInfo);
        return R.ok();
    }

    /**
     * 删除泵库
     */
    @PostMapping(value = "/delete")
    @ApiOperation("删除泵库(web)")
    @Login
    public R delete(@RequestBody Integer[] ids) {
        //假删除
        CfgPumpInfo p = new CfgPumpInfo();
        p.setStatus(-1);
        cfgPumpInfoService.update(p, new UpdateWrapper<CfgPumpInfo>().in(CfgPumpInfo.ID, Arrays.asList(ids)));
        return R.ok();
    }

    /**
     * 修改泵库
     */
    @PostMapping(value = "/update")
    @ApiOperation("修改泵库(web)")
    @Login
    public R update(@RequestBody CfgPumpInfo cfgPumpInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgPumpInfoService.updatePump(cfgPumpInfo);
        return R.ok();
    }

    /**
     * 获取泵修改日志
     */
    @GetMapping(value = "/logList")
    @ApiOperation("获取泵修改日志(web)")
    @Login
    public R logList(@RequestParam Map<String, Object> params) {
        PageUtils page = cfgPumpInfoService.logList(params);
        return R.ok().put(Constant.DATA, page);
    }

    /**
     * 修改连接点
     */
    @PostMapping(value = "/updateRelate")
    @ApiOperation("修改连接点(web)")
    @Login
    public R updateRelate(@RequestBody List<CfgPumpRelate> pumpRelateList) {
        cfgPumpInfoService.updateRelate(pumpRelateList);
        return R.ok();
    }

    /**
     * app修改rfid
     */
    @PostMapping(value = "/updateRfid")
    @ApiOperation("app修改rfid(app)")
    @Login
    public R updateRfid(@RequestBody CfgPumpInfo cfgPumpInfo, @ApiIgnore @LoginUser SysUserEntity user) {
        MDC.put("deptUser", user.getDeptName() + "-" + user.getName());
        cfgPumpInfoService.updateRfid(cfgPumpInfo);
        return R.ok();
    }

    /**
     * 获取泵库
     */
    @GetMapping(value = "/get/{id}")
    @ApiOperation("获取泵库(web/app)")
    @Login
    public R get(@PathVariable("id") Long id) {
        CfgPumpInfo pump = cfgPumpInfoService.getById(id);
        CfgPumpProduct PumpProduct = cfgPumpProductService.getOne(new LambdaQueryWrapper<CfgPumpProduct>().eq(CfgPumpProduct::getPumpId, pump.getId()));
        pump.setPumpProduct(PumpProduct);
        return R.ok().put(Constant.DATA, pump);
    }

    /**
     * 查看泵连接点
     */
    @GetMapping(value = "/getRelateObject")
    @ApiOperation("查看泵连接点(web/app)")
    @Login
    public R getRelateObject(@RequestParam Integer pumpId) {
        List<CfgPumpRelate> relates = cfgPumpInfoService.getRelateObject(pumpId);
        return R.ok().put(Constant.DATA, relates);
    }

    /**
     * 查看泵可用连接点
     */
    @GetMapping(value = "/getValidRelateObject")
    @ApiOperation("查看泵可用连接点(web)")
    @Login
    public R getValidRelateObject(ValidPumpParam param) {
        List<CfgPumpRelate> relates = pumpRelateService.getValidRelateObject(param);

        List<Integer> selectedPumpIds = param.getSelectedPumpIds();
        List<Integer> selectedTubeIds = param.getSelectedTubeIds();
//        List<Integer> selectedPotIds = param.getSelectedPotIds();//已选中的罐id
//        List<Integer> selectedBerthIds = param.getSelectedBerthIds();//已选中的泊位id
        if (CollectionUtils.isNotEmpty(selectedPumpIds)) {
            Iterator<CfgPumpRelate> it = relates.iterator();
            while (it.hasNext()) {
                CfgPumpRelate r = it.next();
                if (3 == r.getType().intValue() && selectedPumpIds.contains(r.getRelateId())) {
                    it.remove();
                }
            }
        }
        if (CollectionUtils.isNotEmpty(selectedTubeIds)) {
            Iterator<CfgPumpRelate> it = relates.iterator();
            while (it.hasNext()) {
                CfgPumpRelate r = it.next();
                if (2 == r.getType().intValue() && selectedTubeIds.contains(r.getRelateId())) {
                    it.remove();
                }
            }
        }

        return R.ok().put(Constant.DATA, relates);
    }

    /**
     * 修改泵连接点
     */
    @PostMapping(value = "/updateRelateObject")
    @ApiOperation("修改泵连接点(web)")
    @Login
    public R updateRelateObject(@RequestBody List<CfgPumpRelate> relates) {
        cfgPumpInfoService.updateRelateObject(relates);
        return R.ok();
    }

    @GetMapping(value = "/logExport")
    @ApiOperation("泵操作记录导出")
    @Login
    public void logExport(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        Object pumpId = params.get("id");
        CfgPumpInfo pump = cfgPumpInfoService.getOne(new LambdaQueryWrapper<CfgPumpInfo>().eq(CfgPumpInfo::getId, pumpId).select(CfgPumpInfo::getId, CfgPumpInfo::getNumberNo));
        PageUtils page = cfgPumpInfoService.logList(params);
        List list = page.getList();
        String fileName = "泵(" + pump.getNumberNo() + ")操作记录";
        String sheetName = "泵操作记录";
        String[] headers = {"记录时间", "操作人", "目前产品", "RFID"};
        String[] columns = {"createTime", "deptUser", "comProductInfo", "rfidInfo"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }

    @GetMapping(value = "/export")
    @ApiOperation("泵列表导出")
    @Login
    public void export(HttpServletResponse response, @RequestParam Map<String, Object> params) {
        ExportExcel exportExcel = new ExportExcel();
        params.put("limit", "650000");
        PageUtils page = cfgPumpInfoService.queryPage(params);
        List list = page.getList();
        String fileName = "泵数据";
        String sheetName = "sheet1";
        String[] headers = {"泵编号", "位置1", "位置2", "目前产品", "材质", "保温", "RFID"};
        String[] columns = {"numberNo", "position1", "position2", "comUsedProd", "texture", "insulation", "rfid"};
        try {
            exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RRException(RRExceptionEnum.EXPORT_FAIL);
        }
    }

}
